package com.xinyue.authorization.dao.impl;

import com.xinyue.authorization.bean.UserRole;
import com.xinyue.authorization.dao.UserRoleDao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xinyue.authorization.bean.User;
import com.xinyue.authorization.bean.Role;

@Repository("UserRoleDaoImpl")
public class UserRoleDaoImpl implements UserRoleDao {
	@Autowired
    private SessionFactory factory;
    
	//默认方法
	public void save(UserRole entity) {
		factory.getCurrentSession().save(entity);
	}
	
	public Integer deleteById(int id) {
		Query q = factory.getCurrentSession().createQuery("delete UserRole where id=?");
		q.setParameter(0, id);
		return q.executeUpdate();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> queryUserByRoleId(int roleId) {
		Query q = factory.getCurrentSession().createQuery("select o from UserRole a,User o where o.userId=a.userId and a.roleId=?");
		q.setParameter(0, roleId);
		return q.list();
	};
	
	@SuppressWarnings("unchecked")
	public List<Role> queryRoleByUserId(int userId) {
		Query q = factory.getCurrentSession().createQuery("select o from UserRole a,Role o where o.roleId=a.roleId and a.userId=?");
		q.setParameter(0, userId);
		return q.list();
	};
	
	public Integer deleteByUserId(int userId) {
		Query q = factory.getCurrentSession().createQuery("delete UserRole where userId=:userId");
		q.setParameter(0, userId);
		return q.executeUpdate();
	};
	
	public Integer deleteByRoleId(int roleId) {
		Query q = factory.getCurrentSession().createQuery("delete UserRole where roleId=:roleId");
		q.setParameter(0, roleId);
		return q.executeUpdate();
	};
}